import {getAccount, postAccount, putAccount} from '@/base/api/AccountApi';
import {Account} from '@/base/model/Account';

export class FormBloc {
  form = new Account();
  hasFormInfo = false;

  load(id: number) {
    return getAccount(id)
      .then((res) => {
        let dataItem = res.data;
        this.form.id = dataItem.id;
        this.form.userName = dataItem.userName;
        this.form.email = dataItem.email;
        this.form.phone = dataItem.phone;
        this.form.repeatPassword = dataItem.password;
        // @ts-ignore
        this.form.roles = dataItem.roles.map(x => Number(x)) || [];
        this.form.password = dataItem.password;
        this.form.companyId = dataItem.companyId;
        return res;
      }).finally(() => {
        this.hasFormInfo = true
      })
  }

  save(id: number | '') {
    const entity: any = {
      email: this.form.email,
      phone: this.form.phone,
      roles: this.form.roles,
      userName: this.form.userName,
      type: 'MANAGE',
    };
    if (!id) {
      entity.password = this.form.password;
    }
    // @ts-ignore
    return id ? putAccount(id, entity) : postAccount(entity);
  }
}
